#!/bin/bash
file_name=functions.sh
funcs=`which $file_name`
if [ "$funcs" != "" ] ;then
  echo "funcs=$funcs"
  . $funcs
else
  funcs=`dirname $0`/$file_name
  echo "$PWD"
  echo "funcs=$funcs"
  if [ "$funcs" != "" ] ;then
    . $funcs
  else
    exit
  fi
fi

# =====================================================
# constants
# =====================================================

DEST=update.json
MODEL_LIST=(VIVOV1 VIVOY1 VIVOS1 VIVOS3 VIVOS6 VIVOS7 VIVOS9 VIVOS12 VIVOE3 VIVOE7)

# =====================================================
# variable
# =====================================================

dir_files=

# =====================================================
# usage
# =====================================================

function PrintUsage()
{
color.sh "
============================ usage ============================
usage: generate upload json file to upload update package 
description: null
param: 1: dir of patch update package
============================= end =============================\n" 3 0 1
}

# =====================================================	
# functions
# =====================================================

function WriteToFile()
{
	if [ -z $2 ]; then 
		echo "$1" >> $DEST
	else
		echo $1 "$2" >> $DEST
	fi
}

function GenFileNameList()
{
	local dir=$1
	local list=`ls $dir | grep patch | grep zip`
	local len=`ls $dir | grep patch | grep zip | wc -l`
	local item
	local index=1
	local filemd5=

	WriteToFile "	\"fileName\":"
	WriteToFile "	[" 

	echo "len = $len" >&2
	for item in ${list[*]} 
	do
		filemd5=`md5sum $item  | awk '{print $1}'`
		WriteToFile  -n "		{\"name\":\"$item\",\"md5\":\"$filemd5\"}" 

		if [ $index -eq $len ]; then
			WriteToFile "" 
		else
			WriteToFile ","
		fi

		((index++))
	done
	WriteToFile "	]"
}

function GenPhoneModel()
{
	local model
	echoTextGreen "Choose the phone model"
	select model in ${MODEL_LIST[*]}
	do
		if [ "x$model" != "x" ]; then
			break
		fi
	done

	WriteToFile "	\"mobileType\":\"$model\","
}

function GenSWVersion()
{
	local version
	version=`question  "Input software version(example:1.1.1):"  2`
	WriteToFile "	\"version\":\"$version\","
}

function GenHWVersion()
{
	local version
	version=`question  "Input hardware version(example:PD1203MA):"  2`
	WriteToFile "	\"hardwareVersion\":\"$version\","
}

function GenDescription()
{
	WriteToFile "	\"description\":\"\","
}

# =====================================================
# script body
# =====================================================

dir_files=$1
if [ -z $dir_files ]; then
	dir_files=`pwd`
fi
echoTextBlue "dir_files = $dir_files"

rm -vf $DEST

WriteToFile "{"
GenPhoneModel
GenSWVersion
GenHWVersion
GenDescription
GenFileNameList $dir_files
WriteToFile "}"

cat $DEST
